package com.usian.controller;

import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.usian.service.UserService;

import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //显示全部
    @RequestMapping("findAll")
    public String findAll(Model model){
        //分页（总页数，一页几条，总条数）
        List<User> userList=userService.findAll();
        model.addAttribute("user",userList);
        return "list";
    }


    //根据id查询
    @RequestMapping("/findById/{id}")
    public String findById(@PathVariable Integer id,Model model){
        User user=userService.findById(id);
        model.addAttribute("user",user);
        return "add";
    }

    //添加用户信息
    @PostMapping("addUser")
    public String addUser(User user){
        //有id就是修改，没id就是添加
        if(user.getUserld()!=null){
            userService.update(user);
        }else{
            userService.addUser(user);
        }
        return "redirect:/user/findAll";
    }


    //根据id删除
    @RequestMapping("del/{id}")
    public String del(@PathVariable Integer id){
        userService.del(id);
        return "redirect:/user/findAll";
    }

    //到添加页面
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        //因为添加和修改都是同一个页面，所以要先给添加页面设为空
        User user = new User();
        model.addAttribute("user",user);
        return "add";
    }
}
